package day11;

import java.util.concurrent.locks.ReentrantReadWriteLock;

//测试读写锁
public class TestReadWrite {
    Object data;//数据
    ReentrantReadWriteLock rwlock = new ReentrantReadWriteLock();

    public void read() {
        try {
            String name = Thread.currentThread().getName();
            rwlock.readLock().lock();
            //怎么读取
            System.out.println(name + "开始读写2S数据" + data);
            Thread.sleep(2000);
            System.out.println(name + "结束读写2S数据" + data);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            rwlock.readLock().unlock();
        }
    }

    public void write(Object data) {
        try {
            String name = Thread.currentThread().getName();
            rwlock.writeLock().lock();
            //怎么写入
            System.out.println(name + "开始写入2S数据" + data);
            Thread.sleep(2000);
            this.data = data;
            System.out.println(name + "结束写入2S数据" + data);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            rwlock.writeLock().unlock();
        }
    }

    public static void main(String[] args) {
        TestReadWrite trw = new TestReadWrite();
        for (int i = 0; i < 3; i++) {
            new Thread(() -> {
                for (int j = 0; j < 5; j++) {
                    trw.read();
                }
            }, "读:" + i).start();
            new Thread(() -> {
                for (int j = 0; j < 5; j++) {
                    trw.write(System.currentTimeMillis());
                }
            }, "写:" + i).start();
        }
    }
}
